package com.inspur.jzsxxzx.service.catalog.impl;

import com.inspur.jzsxxzx.entity.catalog.DataCatalogCategory;
import com.inspur.jzsxxzx.mapper.catalog.DataCatalogCategoryMapper;
import com.inspur.jzsxxzx.service.catalog.DataCatalogCategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class DataCatalogCategoryServiceImpl implements DataCatalogCategoryService {

    @Autowired
    private DataCatalogCategoryMapper dataCatalogCategoryMapper;

    @Override
    public int save(DataCatalogCategory record) {
        return dataCatalogCategoryMapper.insert(record);
    }

    @Override
    public DataCatalogCategory findById(String id) {
        return dataCatalogCategoryMapper.selectByPrimaryKey(id);
    }

    @Override
    public int update(DataCatalogCategory record) {
        return dataCatalogCategoryMapper.updateByPrimaryKey(record);
    }

    @Override
    public int deleteById(String id) {
        return dataCatalogCategoryMapper.deleteByPrimaryKey(id);
    }

    @Override
    public List<DataCatalogCategory> findAll() {
        return dataCatalogCategoryMapper.selectAll();
    }

    @Override
    public List<DataCatalogCategory> findByCondition(DataCatalogCategory condition) {
        return dataCatalogCategoryMapper.selectByCondition(condition);
    }

    @Override
    public List<DataCatalogCategory> findByPage(DataCatalogCategory condition, int pageNum, int pageSize) {
        int offset = (pageNum - 1) * pageSize;
        return dataCatalogCategoryMapper.selectByPage(condition, offset, pageSize);
    }

    @Override
    public int countByCondition(DataCatalogCategory condition) {
        return dataCatalogCategoryMapper.countByCondition(condition);
    }

    @Override
    public String getCategoryPathName(String id) {
        // 获取当前节点
        DataCatalogCategory current = findById(id);
        if (current == null) {
            return null;
        }

        // 使用列表存储路径上的所有节点名称
        java.util.List<String> names = new java.util.ArrayList<>();

        // 递归获取所有父级节点名称
        findParentNames(current, names);

        // 反转列表，使顺序从根节点到当前节点
        java.util.Collections.reverse(names);

        // 用-连接所有名称
        return String.join("-", names);
    }

    /**
     * 递归查找所有父级节点的名称
     * 
     * @param category 当前分类节点
     * @param names    名称列表
     */
    private void findParentNames(DataCatalogCategory category, java.util.List<String> names) {
        // 添加当前节点名称
        names.add(category.getName());

        // 如果pid不为空且不为空字符串，继续查找父级节点
        if (category.getPid() != null && !category.getPid().isEmpty() && !category.getPid().equals("''")) {
            DataCatalogCategory parent = dataCatalogCategoryMapper.selectByPid(category.getPid());
            if (parent != null) {
                findParentNames(parent, names);
            }
        }
    }
}